// components/dots/index.js
import Common from '../../common/common.js';
let common = new Common;
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    imageList: {
      type: Array,
      value: []
    }
  },

  ready() {
    this.setData({
      imgList: this.properties.imageList
    })
  },

  /**
   * 组件的初始数据
   */
  data: {
    imgList: []
  },

  /**
   * 组件的方法列表
   */
  methods: {
    ChooseImage(e) {
      wx.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: (res) => {
          this.uploadImage(res.tempFilePaths[0])
        }
      });
    },
    ViewImage(e) {
      wx.previewImage({
        urls: this.data.imgList,
        current: e.currentTarget.dataset.url
      });
    },
    DelImg(e) {
      wx.showModal({
        title: '提示',
        content: '确定要删除这张图片吗？',
        success: res => {
          if (res.confirm) {
            this.data.imgList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
              imgList: this.data.imgList
            })
            this.changeImage();
          }
        }
      })
    },
    uploadImage(file, type) { //type 1上传 2修改 
      wx.showToast({
        title: '上传中...', 
        icon: 'loading'
      })
      wx.uploadFile({
        url: `${common.requestApi}/api/file-service/v1/file/uploadFile`,
        filePath: file,
        header: {
          "token": wx.getStorageSync('token')
        },
        name: 'file',
        formData: {},
        success: (res) => {
          console.log(res);
          let data = JSON.parse(res.data);
          console.log(data);
          let array = [...this.data.imgList];
          array.push(data.result);
          this.setData({
            imgList: array
          })
          wx.hideLoading();
          console.log('this.data.imgList', this.data.imgList)
          this.changeImage();
        },
        fail: (err) => {
          wx.showToast({
            title: '图片上传失败,请重试！',
            icon: "none"
          })
        }
      })
    },
    changeImage() {
      this.triggerEvent('changeImage', this.data.imgList);
    }
  }
})